package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> list = this.list();
        List<CategoryEntity> level1List = list.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0).collect(Collectors.toList());
        //2、组装父子结构
        return level1List.stream().peek(category -> category.setChildren(getChildren(category, list)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> list) {
        //todo 检查当前删除的菜单是否被其他地方引用
        baseMapper.deleteBatchIds(list);
    }

    @Override
    public Long[] findCateLogPath(Long cateLogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(cateLogId, paths);
        Collections.reverse(parentPath);
        return paths.toArray(new Long[parentPath.size()]);
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 0));
        return categoryEntities;
    }

    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        //缓存中存入json字符串
        Map<String, List<Catalog2Vo>> catalogJsonFromDb = Collections.emptyMap();
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isBlank(catalogJSON)) {
            catalogJsonFromDb = getCatalogJsonRedisLock();
        } else {
            catalogJsonFromDb = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {});
        }
        return catalogJsonFromDb;
    }

    //分布式锁
    private Map<String, List<Catalog2Vo>> getCatalogJsonRedisLock() {
        String uuid = UUID.randomUUID().toString();
        Map<String, List<Catalog2Vo>> catalogJsonFromDb = Collections.emptyMap();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock){
            try{
                log.debug("获取分布式锁成功。。。");
                catalogJsonFromDb = doubleDetection();
            }finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return  redis.call('del', KEYS[1]) else return 0 end";
                //删除所
                Long lockResult = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
        }else{
            log.debug("获取分布式锁失败。。。");
            //加锁重试
            //休眠100ms重试
            return getCatalogJsonRedisLock();
        }
        return catalogJsonFromDb;
    }

    private Map<String, List<Catalog2Vo>> getCatalogJsonLocal() {
        Map<String, List<Catalog2Vo>> catalogJsonFromDb = Collections.emptyMap();
        synchronized (this) {
            catalogJsonFromDb = doubleDetection();
        }
        return catalogJsonFromDb;
    }

    private Map<String, List<Catalog2Vo>> doubleDetection() {
        Map<String, List<Catalog2Vo>> catalogJsonFromDb;
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isBlank(catalogJSON)) {
            catalogJsonFromDb = getCatalogJsonFromDb();
            redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(catalogJsonFromDb));
        }else{
            catalogJsonFromDb = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {});
        }
        return catalogJsonFromDb;
    }

    //从数据库查询并封装业务数据
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDb() {
        System.out.println("查询了数据库");

        //将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);

        //1、查出所有分类
        //1、1）查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        //封装数据
        Map<String, List<Catalog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());

            //2、封装上面的结果
            List<Catalog2Vo> Catalog2Vos = null;
            if (categoryEntities != null) {
                Catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo Catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());

                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null) {
                        List<Catalog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catalog2Vo.Category3Vo category3Vo = new Catalog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return category3Vo;
                        }).collect(Collectors.toList());
                        Catalog2Vo.setCatalog3List(category3Vos);
                    }

                    return Catalog2Vo;
                }).collect(Collectors.toList());
            }

            return Catalog2Vos;
        }));

        return parentCid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, long parentCid) {
        List<CategoryEntity> categoryEntities = selectList.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
        return categoryEntities;
    }

    private List<Long> findParentPath(Long cateLogId, List<Long> paths) {
        paths.add(cateLogId);
        CategoryEntity byId = this.getById(cateLogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    private List<CategoryEntity> getChildren(CategoryEntity category, List<CategoryEntity> all) {
        return all.stream().filter(item -> Objects.equals(item.getParentCid(), category.getCatId()))
                .peek(child -> child.setChildren(getChildren(child, all)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
    }

}